package com.sayice.gomoku.web;

import com.sayice.gomoku.game.Action;
import com.sayice.gomoku.pojo.MsgInfo;
import com.sayice.gomoku.pojo.User;
import com.sayice.gomoku.service.UserService;
import com.sayice.gomoku.service.impl.UserServiceImpl;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;

/**
 * 登录
 */
@ServerEndpoint(value = "/login/{name}/{password}")
public class LoginSocket {
    private final UserService userService = new UserServiceImpl();
    
    private Session session;
    
    @OnOpen
    public void onOpen(@PathParam("name") String name, @PathParam("password") String password, Session session) throws IOException {
        System.out.println("虚幻客户端登录请求");
        this.session = session;
        name = name.trim();
        password = password.trim();
        User user = new User();
        user.setName(name);
        user.setPassword(password);
        User loginUser = userService.login(user);
        if (loginUser == null) {
            System.out.println("用户名或密码错误！");
            send(Action.loginFail, null);
            session.close();
            return;
        }
        System.out.println("用户登录成功");
        send(Action.setId, loginUser.getId());
        session.close();
    }
    
    @OnClose
    public void onClose() throws IOException {
        System.out.println("虚幻客户端登录请求处理完成");
    }
    
    @OnMessage
    public void onMessage(String msg) {
    
    }
    
    private void send(Action action, Object data) throws IOException {
        synchronized (this) {
            session.getBasicRemote().sendText(new MsgInfo(action, data).toJson());
        }
    }
}
